import Editor from "@/tool/Editor";
import { SelectEvent } from "@/tool/eventType";
import { PluginTempl } from "@/tool/PluginTempl";

enum typeKey {
  lockMovementX = "lockMovementX",
  lockMovementY = "lockMovementY",
  lockRotation = "lockRotation",
  lockScalingX = "lockScalingX",
  lockScalingY = "lockScalingY",
}

enum IControlKey {
  bl = "bl",
  br = "br",
  mb = "mb",
  ml = "ml",
  mr = "mr",
  mt = "mt",
  tl = "tl",
  tr = "tr",
  mtr = "mtr",
  lock = "lock",
}

export default class lockPlugin implements PluginTempl {
  static apis = ['lock', 'unLock'];
  constructor(public canvas: fabric.Canvas, public editor: Editor) {
    this.init();
  }
  init() {}

  lock() {
    const activeObject = this.canvas.getActiveObject() as fabric.Object;
    if (activeObject) {
      // 修改默认属性
      Object.values(typeKey).forEach((key: typeKey) => {
        activeObject[key] = true;
      });
      this.controlCornersVisible(activeObject);
      this.canvas.renderAll();
      this.editor.emit(SelectEvent.ONE, [activeObject]);
    }
  }

  unLock() {
    const activeObject = this.canvas.getActiveObject() as fabric.Object;
    if (activeObject) {
      activeObject.hasControls = true;
      activeObject.selectable = true;
      activeObject.evented = true;
      // 修改默认属性
      Object.values(typeKey).forEach((key: typeKey) => {
        activeObject[key] = false;
      });
      this.controlCornersVisible(activeObject);
      this.canvas.renderAll();
      this.editor.emit(SelectEvent.ONE, [activeObject]);
    }
  }

  controlCornersVisible(obj: fabric.Object) {
    const isLocked: boolean = obj.lockMovementX == true;
    Object.values(IControlKey).forEach((key: IControlKey) => {
      if (key === IControlKey.lock) {
        obj.setControlVisible(key, isLocked);
      } else {
        obj.setControlVisible(key, !isLocked);
      }
    });
  }
}
